<?php

namespace App\Http\Controllers\Admin\V1;

use App\Exports\ExaminationExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ExaminationRequest;
use App\Models\Examination;
use App\Models\Role;
use App\Models\User;
use App\Transformers\Admin\DetailTransformer;
use App\Transformers\Admin\ExaminationTransformer;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Maatwebsite\Excel\Facades\Excel;


class ExaminationController extends Controller
{
    /**
     * 考试列表
     *
     * @return Response
     */
    public function index()
    {
        $root = $this->adminUser()->user()->hasRole(Role::SUPER_ADMIN);

        $ids = userIdAndAllChildrenId();

        $data = Examination::pimp()
            ->when(!$root, function ($query) use ($ids) {
                $query->whereIn('user_id', $ids);
            })
            ->select('id', 'category_id', 'name', 'start_time', 'over_time', 'timer', 'peoples', 'subject_id', 'user_id', 'status')
            ->orderBy('start_time', 'desc')
            ->paginate($this->pageLimit());

        return $this->response->paginator($data, new ExaminationTransformer());
    }

    /**
     * 添加考试
     * @param ExaminationRequest $request
     * @return Response|void
     */
    public function store(ExaminationRequest $request)
    {
        //追加reviewer的值如果没有，当前登录的用户就是评卷人
        $request->offsetSet('reviewer', $request->input('reviewer') ?? auth()->id());

        // 被考人 ,3,4,5,
        if (empty($request->input('peoples'))) {
            $request->offsetSet('peoples', 0);
        } else {
            $peoples = ',' . implode(',', $request->input('peoples')) . ',';

            $request->offsetSet('peoples', $peoples);
        }


        //把请求中的reviewer的值用逗号分割成一个数组
        $reviewers = explode(',', $request->input('reviewer'));

        //在把数组中的值与用户表里的id进行比对
        $user = User::query()->whereIn('id', $reviewers)->pluck('id')->toArray();

        //在把数组中的值与查出来的值进行求差
        $result = collect($reviewers)->diff($user);

        //如果差值不为空就返回
        if ($result->isNotEmpty()) {
            return $this->response->errorBadRequest('用户不存在');
        }
        //把创建人追加进去
        $request->offsetSet('user_id', auth()->id());

        //添加请求中的所有数据
        Examination::create($request->all());

        return $this->response->created();
    }

    /**
     * 考试详情
     *
     * @param Examination $examination
     * @return Response
     * @throws AuthorizationException
     */
    public function show(Examination $examination)
    {
        //进行授权
        $this->authorize('view', $examination);

        return $this->response->item($examination, new DetailTransformer());
    }

    /**
     * 更新考试
     *
     * @param ExaminationRequest $request
     * @param Examination $examination
     * @return Response|void
     * @throws AuthorizationException
     */
    public function update(ExaminationRequest $request, Examination $examination)
    {
        //进行授权
        $this->authorize('update', $examination);

        // 被考人 ,3,4,5,
        if (empty($request->input('peoples'))) {
            $request->offsetSet('peoples', 0);
        } else {
            $peoples = ',' . implode(',', $request->input('peoples')) . ',';

            $request->offsetSet('peoples', $peoples);
        }

        //追加reviewer的值如果没有，当前登录的用户就是评卷人
        $request->offsetSet('reviewer', $request->input('reviewer') ?? auth()->id());

        //把请求中的reviewer的值用逗号分割成一个数组
        $reviewers = explode(',', $request->input('reviewer'));

        //在把数组中的值与用户表里的id进行比对
        $user = User::query()->whereIn('id', $reviewers)->pluck('id')->toArray();

        //在把数组中的值与查出来的值进行求差
        $result = collect($reviewers)->diff($user);

        //如果差值不为空就返回
        if ($result->isNotEmpty()) {
            return $this->response->errorBadRequest('用户不存在');
        }

        //把创建人追加进去
        $request->offsetSet('user_id', auth()->id());
        //修改请求中的所有数据
        $examination->update($request->all());

        return $this->response->noContent();
    }

    /**
     * 删除考试
     *
     * @param $ids
     * @return Response
     * @throws AuthorizationException
     */
    public function destroy($ids)
    {
        // 分割传过来的id
        $idArr = explode(',', $ids);

        foreach (Examination::whereIn('id', $idArr)->get() as $examination) {
            //进行授权
            $this->authorize('delete', $examination);
            //执行删除
            $examination->delete();
        }

        return $this->response->noContent();
    }

    /**
     * 导出
     */
    public function export(Request $request)
    {
        return Excel::download(new ExaminationExport($request), 'examination.xlsx', \Maatwebsite\Excel\Excel::XLSX);
    }

    /**
     * 延时考试
     * @param Request $request
     * @param Examination $examination
     * @return \Dingo\Api\Http\Response
     */
    public function delayed(Request $request, Examination $examination)
    {
        $request->validate([
            'timer' => 'required|integer',
        ]);

        $examination->timer = $request->input('timer');

        $examination->save();

        return $this->response->noContent();
    }

    /**
     *
     * 添加前需要获取的分类数据
     *
     * @return \Dingo\Api\Http\Response
     */
    public function getCategoryList()
    {
        // 获取考试分类
        $examination = cacheExamination();

        // 获取科目分类
        $subject = cacheSubject();

        return $this->response->array(['examination' => $examination, 'subject' => $subject]);
    }
}
